package 强化训练;

import java.util.Scanner;

public class day28反转部分链表 {

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int countNode= sc.nextInt();
        int[] nodes = new int[countNode];
        Node temp = new Node();//临时节点
        Node head = temp;//头节点
        for (int i = 0; i < countNode; i++) {
            int val = sc.nextInt();
            Node newNode = new Node(val);//传入的值直接创建一个节点
            temp.next = newNode;//让临时节点的next指向新的节点
            temp = newNode;//在让临时节点指向当前新的节点，采用尾插法
        }
        head = head.next;//最后将空的头节点去掉
        int left = sc.nextInt();
        int right = sc.nextInt();
        Node preNode = head;//要反转的前一个节点
        Node leftNode = head;//要反转的第一个节点
        Node lastNode = head;//要反转的最后一个节点下一个节点
        Node rightNode = head;//要反转的最后一个节点
        for (int i = 1; i < left - 1; i++) {
            if (preNode != null){
                preNode = preNode.next;
            }
        }
        //找到反转链表的头节点的前一个节点
        if (left == 1){
            leftNode = head;
        }else {
            if (preNode != null){
                leftNode = preNode.next;
            }
        }
        //找到要反转的最后一和节点
        for (int i = 0; i < right-1; i++) {
            if (rightNode != null){
                rightNode = rightNode.next;
            }
        }
        //找到右节点的后一节点
        if (rightNode != null){
            lastNode = rightNode.next;
        }
        //反转链表,此时rightNode为反转后的链表的头节点，leftNode为尾节点
        Node node = reversePartList(leftNode, rightNode);
        //如果是从第一个位置就开始反转，那么就直接拼接lastNode到反转后的链表中
        if (left == 1){
            head = node;
            leftNode.next = lastNode;
        }else {
            preNode.next = rightNode;
            leftNode.next = lastNode;
        }
        while (head != null){
            System.out.print(head.val + " ");
            head = head.next;
        }
    }


    /**
     * 传入左右节点，原地反转链表
     * @param left 左节点
     * @param right 有节点
     * @return 返回反转后的链表
     */
    private static Node reversePartList(Node left,Node right){
        Node dummyHead = new Node();
        Node cur = left;
        while (cur != right){
            Node next = cur.next;
            cur.next = dummyHead;
            dummyHead = cur;
            cur = next;
        }
        //此时，cur等于右节点
        cur.next = dummyHead;
        dummyHead = cur;
        return dummyHead;
    }
}
class Node{
    int val;
    Node next;
    public Node(){}
    public Node(int val){
        this.val = val;
    }
}
